package com.eshop.web.page;

import com.eshop.dao.CategoryDao;
import com.eshop.dao.ProductDao;
import com.eshop.domain.Category;
import com.eshop.domain.Product;
import com.eshop.web.component.CategoriesTree;
import com.eshop.web.component.ProductsListView;
import com.eshop.web.page.template.BaseTemplate;
import com.eshop.web.page.template.LeftCenterColumns;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.tree.BaseTree;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.Collections;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Sergey
 * Date: 17.10.13
 * Time: 0:32
 * To change this template use File | Settings | File Templates.
 */
public class IndexPage extends LeftCenterColumns {
    private static final Logger LOGGER = LoggerFactory.getLogger(IndexPage.class);

    @SpringBean(name = "productDao")
    private ProductDao productDao;

    @SpringBean(name = "categoryDao")
    private CategoryDao categoryDao;

    private ProductsListView productsListView;
    private List<Product> productList;

    public IndexPage() {
        productList = productDao.load();

        mainMarkupContainer.add(new Label("leftSidebarName", "Категории товаров"));

        mainMarkupContainer.add(new CategoriesTree("leftSidebarContent", categoryDao.loadTree()) {
            @Override
            protected void onNodeLinkClicked(Object node, BaseTree tree, AjaxRequestTarget target) {
                super.onNodeLinkClicked(node, tree, target);

                DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                Category category = (Category) treeNode.getUserObject();
                List<Category> categories = categoryDao.loadLeafsOfParent(category);
                productList = productDao.loadByCategories(categories);

                target.add(mainMarkupContainer);
            }
        });

        IModel<List<? extends Product>> productListIModel
                = new AbstractReadOnlyModel<List<? extends Product>>() {
            @Override
            public List<Product> getObject() {
                if (productList == null)
                    productList = Collections.emptyList();
                return productList;
            }

        };

        productList = productDao.load();
        productsListView = new ProductsListView("listItem", "content", productListIModel);
        mainMarkupContainer.add(productsListView);
    }
}
